State in React


In this article, we will understand the concept of State in React and its importance. In our previous article, We have discussed about properties and their ready-only behavior. 

Application UIs are dynamic and change over time. And any changes we do on the Component Class members for various user actions should get updated into Browser UI. Now question is as our props are read only , how do we address this. To understand it in Practical, I have opened our demo-project we have created in our Previous Sessions and running it in the local environment.

Lets Open index.js , create a Component Class called Employee and we implement render method. Lets return div which contains one h2 tag and display text called Employee Component and place a button in the Text with Text as Add Employee. Lets Create a function called AddEmployee, in which lets show a simple alert message and to call this function on Click of the button, we use onClick attribute and lets Pass the AddEmployee to it. Lets Call this Component and render it to our DOM. Lets save these changes, navigate to our browser. And we can see the Employee Component contents are being shown.

class Employee extends React.Component {
    addEmployee = () => {
        alert('Clicked on addEmployee Method');
    }
    render() {
      return <div>
          <h2>Employee Component...</h2>
          <button onClick={this.addEmployee}>Add Employee</button>
      </div>
    }
  }

  const element1=<Employee></Employee>
  ReactDOM.render(element1,document.getElementById("root"));

Click on the Button and we can see the alert is being shown with the message. Now lets say we want to keep a track on how many times the button is being Clicked. Lets create a counter variable and initialize with zero. In AddEmployee function, lets increment this counter and display that in the alert.

count=0;
    addEmployee = () => {
        this.count=this.count+1;
        alert(this.count);
        alert('Clicked on addEmployee Method');
    }

Lets save these and navigate to the browser, Click on the button several times and one can see that counter is incremented each time when the button is Clicked. Lets delete the alerts we are showing and create one paragraph element and display the counter value in it. Lets save these and navigate to the browser, Click on the button several times and one can see that counter is not incremented each time when the button is Clicked. That’s because the change we are doing on the counter property in the component class is not getting rendered into our UI.

Lets see how we can solve this in React. React introduces, a new concept named “state” which allows React components to change their output over time in response to user actions without violating this rule.

State is similar to props, but it is private and fully controlled by the component. 

State contains data specific to a given component that may change over time. 

The state is user defined plain javascript object.

By adding a “local state” to a class, we can move data from the props onto a state which can be updated. Lets create state object, add counter property in that object with a default value of 0. When the addEmployee method is Called, we have to incremenet the counter and this change should be updated in the UI. React provides a method called setState()  for managing  component states.  

setState() tells React that this component and its children (sometimes delayed and grouped into a single batch) should be re-rendered with the most updated state. Lets Pass an Object which contains counter and write an arrow function which increments the Counter.  Lets display the counter value from the state object we have created. Save these changes, go back to the browser and one can see that counter value is increment on multiple button clicks.

class Employee extends React.Component {
    state={count:0};
    addEmployee = () => {
        this.setState({counter:this.state.counter+1});
    }
    render() {
      return <div>
          <h2>Employee Component...</h2>
          <button onClick={this.addEmployee}>Add Employee</button>  
          <p>
              <label>Add Employee Button is Clicked : <b>{this.state.count}</b></label></p>        
      </div>
    }
  }

To make our understanding better, lets look at another example. Lets say we want to implement a scenario which we all see in many websites. We want to have a textbox where user can enter a message and a label which should display the number of characters entered in the textbox. To implement this, we create a Component Class, Lets Create Constructor with props as the argument, lets make base class constructor call using super. Lets initialize state object with message property in it. Lets set default message as empty.

Lets implement render method, I place a textbox and a label. When user enters the message in the textbox, this count message needs to displayed in the label. Lets create function named onMessageChange which will accept the entered text in the textbox as parameter. Change the state object message to display that Message has these many number of characters. Lets call the function when the input changes by using onChange Event. Lets pass the text in the input element as parameter to onMessageChange function.

class CountCharacters extends React.Component{

    constructor(props){

        super(props);

        this.state={

            message:'',

            counter:10

        };

    }

    onMessageChange(text){
        this.setState({
            message:'Message has '+text.length+' number of Characters'
        });
    }
    render(){
        return <div>
            <h2>Welcome to Count Characters Component...</h2>
            <p>
                <label>Enter Message : <input type="text" 
                            onChange={e=>this.onMessageChange(e.target.value)}></input></label>
            </p>

            <p>
                <label>{this.state.message}</label>
            </p>
            <p>
                <label>{this.state.counter}</label>
            </p>
        </div>
    }
}

Lets Call this in the Component and render this.

const element=<CountCharacters></CountCharacters>

ReactDOM.render(element,document.getElementById("root"));

Save the changes, go back to the browser and as we keep entering the text, we can see that is being displayed in the label. Lets add one more variable to the state object named count and assign it to lets say a default value of 10. Now when the text is changed, we are triggering testClick function and inside that we are calling setState method by passing the State Object which contains only message. We are not passing the counter value. Lets display the Counter Value as well in another label. 

Save the changes, go back to the browser and as we keep entering the text, we can see that Message is being displayed in one label. Counter value is also displayed in another label. State object is holding both Message and counter though we are not passing it again. I believe we have got a fundamental understanding on how we can start managing the state in a react based application, we will discuss more about session management in react in our upcoming articles.

Thank you for watching this Video and have a great day.

For Video Reference





© 2020 Pragimtech. All Rights Reserved.